package thread;

public class ThreadDeadLockDemo {
	
	public static void main(String[] args) {
		DeadLock dl1 = new DeadLock("o1", true);
		DeadLock dl2 = new DeadLock("o2", false);
		dl1.start();
		dl2.start();
	}

}



class DeadLock extends Thread {
	
	private static Object o1 = new Object();
	private static Object o2 = new Object();
	private boolean flag;
	
	public DeadLock( String name,  boolean flag){
		this.flag = flag;
	}
	

	@Override
	public void run() {
		if( flag ){
			this.method1();
		} else {
			this.method2();
		}
	}
	
	
	public void method1(){
		synchronized ( o1 ) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("试图拿到o2的锁....");
			synchronized (o2) {
				System.out.println("拿o2的锁");
			}
			System.out.println("退出o1");
		}
	}
	
	public void method2(){
		synchronized ( o2 ) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("试图拿到o1的锁....");
			synchronized (o1) {
				System.out.println("拿o1的锁");
			}
			System.out.println("退出o2");
		}
	}
	
}
